package com.cloud.security.web;

import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloud.platform.Constants;
import com.cloud.security.model.User;
import com.cloud.security.service.UserService;

@Controller
@RequestMapping("user")
public class UserBean {
	
	@Autowired
	private UserService userService;
	
	/**
	 * unlock system
	 * 
	 * @param password
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/unlock.do")
	public String unlock(@RequestParam("password") String password) {
		
		User u = userService.getUserById(Constants.getLoginUserId());
		
		return (u != null && u.getPassword().equals(password)) ? Constants.VALID_YES
				: Constants.VALID_NO;
	}
	
	/**
	 * account logout
	 * 
	 * @param session
	 * @param response
	 */
	@RequestMapping("/logout.do")
	public void logout(HttpSession session, HttpServletResponse response) {

		try {
			if(session != null) {
				session.invalidate();
			}
			
			response.sendRedirect(Constants.BASEPATH + "index.jsp");
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * get type users list info
	 * 
	 * @param type
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getUsers.do")
	public String getUsers(@RequestParam("type") int type) {

		// search users
		List users = userService.searchUsers(type);
		
		// convert to json format
		JSONArray usersArr = JSONArray.fromObject(users);
		
		return usersArr.toString();
	}

	/**
	 * save user
	 * 
	 * @param type
	 * @param username
	 * @param password
	 * @param email
	 * @param address
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/saveUser.do")
	public String saveUser(@RequestParam("type") int type,
			@RequestParam("username") String username,
			@RequestParam("password") String password,
			@RequestParam("email") String email,
			@RequestParam("address") String address) {
		
		userService.saveUser(type, username, password, email, address);
		
		return "";
	}
}
